import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/mode/list_pagination_model.dart';
import 'package:flutter_smart_heating/pages/information/indoor/temperature/point.dart';
import 'package:flutter_smart_heating/pages/information/widget/filter.dart';
import 'package:flutter_smart_heating/ui/src/pull_to_refresh.dart';
import 'package:flutter_smart_heating/ui/src/slide_panel.dart';
import 'package:flutter_smart_heating/ui/ui.dart';

class InformationIndoorTemperaturePage extends StatefulWidget {
  const InformationIndoorTemperaturePage({super.key});

  @override
  State<InformationIndoorTemperaturePage> createState() =>
      _InformationIndoorTemperaturePageState();
}

class _InformationIndoorTemperaturePageState
    extends State<InformationIndoorTemperaturePage> {
  RefreshController refreshController = RefreshController();
  ListPaginationModel pagination = ListPaginationModel();
  List<dynamic> list = List.filled(20, {}).toList();
  ValueNotifier hasFilter = ValueNotifier<bool>(false);
  PanelController? panelController;
  Map<String, dynamic> filterParams = {};
  String keyword = '';
  fetchData() async {
    var res = await Http.instance.post(
      '/api/information/indoor_temperature/history',
      data: {
        'page': pagination.currentPage,
        'keyword': keyword,
        ...filterParams
      },
    );
    if (res.code == 1) {
      if (pagination.currentPage <= 1) {
        list.clear();
      }
      pagination = ListPaginationModel.fromJson(res.data);
      res.data['data'].forEach(
        (item) => list.add(item),
      );
    }

    setState(() {});
    refreshController.refreshCompleted();
    if (pagination.hasMore) {
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      dismissOnCapturedTaps: true,
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: UiTheme.of(context).match(light: Colors.white),
          title: const Text('室温监测'),
          actions: [
            IconButton(
              onPressed: () {
                if (panelController?.isPanelOpen == true) {
                  panelController?.close();
                } else {
                  panelController?.open();
                }
              },
              icon: ValueListenableBuilder(
                valueListenable: hasFilter,
                builder: (context, state, widget) {
                  return Icon(state ? UiIcons.filter_fill : UiIcons.filter);
                },
              ),
            ),
          ],
        ),
        body: UiLifeCycle(
            onRouteDone: () {
              fetchData();
            },
            child: FilterView(
              filter: 'indoor.temper',
              onCreated: (context, controller, filter) {
                hasFilter.value = filter.state;
                panelController = controller;
              },
              onChange: (filter) {
                hasFilter.value = filter.state;
                setState(() {
                  list = List.filled(20, {}).toList();
                });
                filterParams = filter.params;
                pagination.currentPage = 1;
                fetchData();
              },
              body: Column(
                children: [
                  Container(
                    color: UiTheme.of(context).match(
                      light: Colors.white,
                      dark: Theme.of(context).appBarTheme.backgroundColor,
                    ),
                    padding: const EdgeInsets.only(
                      top: UiTheme.toolbarSpacing,
                      left: UiTheme.spacingX,
                      right: UiTheme.spacingX,
                      bottom: UiTheme.spacingX,
                    ),
                    alignment: Alignment.centerLeft,
                    child: UiSearchBar(
                      placeholder: '搜索企业或监测位置',
                      backgroundColor:
                          UiTheme.of(context).match(light: Colors.grey[100]),
                      onSubmitted: (val) {
                        keyword = val;
                        pagination.currentPage = 1;
                        fetchData();
                      },
                      onClear: () {
                        keyword = '';
                        pagination.currentPage = 1;
                        fetchData();
                      },
                    ),
                  ),
                  const Divider(height: 0),
                  Expanded(
                    child: UiPushToRefresh(
                      controller: refreshController,
                      onRefresh: () {
                        pagination.currentPage = 1;
                        fetchData();
                      },
                      enablePullUp: pagination.lastPage > 1 &&
                          !refreshController.isRefresh,
                      onLoad: () {
                        pagination.currentPage++;
                        fetchData();
                      },
                      child: list.isEmpty
                          ? const Center(child: UiResult())
                          : ListView.builder(
                              itemBuilder: (context, index) {
                                var item = list[index];
                                bool isBlock = item['id'] == null;
                                return UiTap(
                                  onTap: () {
                                    InformationIndoorPointTemperaturePage.show(
                                        context,
                                        id: item['point_id']);
                                  },
                                  child: UiPanel(
                                    margin: const EdgeInsets.only(
                                      left: UiTheme.spacingX,
                                      right: UiTheme.spacingX,
                                      top: UiTheme.spacingX,
                                    ),
                                    padding:
                                        const EdgeInsets.all(UiTheme.spacing),
                                    child: Row(children: [
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            isBlock
                                                ? const UiBlock(
                                                    height: 20,
                                                    width: 250,
                                                  )
                                                : Text(
                                                    item['point_name'] ?? '',
                                                    style: const TextStyle(
                                                      fontSize: 18,
                                                      fontWeight:
                                                          FontWeight.w500,
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                    ),
                                                  ),
                                            const SizedBox(height: 5),
                                            isBlock
                                                ? const UiBlock(
                                                    height: 15,
                                                    width: 150,
                                                    margin: 4,
                                                  )
                                                : Row(
                                                    children: [
                                                      const Icon(
                                                          UiIcons.company,
                                                          size: 15),
                                                      const SizedBox(width: 5),
                                                      Text(
                                                        item['company_name'] ??
                                                            '',
                                                      ),
                                                    ],
                                                  )
                                          ],
                                        ),
                                      ),
                                      const SizedBox(width: 30),
                                      isBlock
                                          ? Container()
                                          : Text(
                                              '${item['temper']}­°C',
                                              style: TextStyle(
                                                color:
                                                    item['status'] == 'abnormal'
                                                        ? Colors.red
                                                        : null,
                                                fontWeight: FontWeight.w500,
                                              ),
                                            ),
                                    ]),
                                  ),
                                );
                              },
                              itemCount: list.length,
                            ),
                    ),
                  ),
                ],
              ),
            )),
      ),
    );
  }
}
